<script setup lang="ts" name="PreviewPanel">
import { useGenerationStore } from '@renderer/stores/useGenerationStore'
import { ElMessage } from 'element-plus'
import { defineAsyncComponent, reactive, ref } from 'vue'
import { useI18n } from 'vue-i18n'


interface MenuItem {
  id: string
  txt: string
  icon: string
  action: 'edit' | 'delete' | 'add' | 'copy'
}

const { t } = useI18n()
const contextmenuRef = ref();
const Contextmenu = defineAsyncComponent(() => import('@renderer/views/common/component/contextmenu.vue'))
const generationStore = useGenerationStore()

const openPreview = (image: string) => {
  generationStore.previewImage = image
}



const state = reactive({
  dropdown: { x: 0, y: 0 },
  customMenuItems: [
    { id: 'copy', txt: t('message.common.copy'), icon: 'ele-DocumentCopy', action: 'copy' },
    { id: 'donwload', txt: t('message.common.save'), icon: 'ele-Download', action: 'download' },
  ] as MenuItem[]
})

const onContextmenu = (v, e: MouseEvent) => {
  const { clientX, clientY } = e;
  state.dropdown.x = clientX;
  state.dropdown.y = clientY;
  contextmenuRef.value.openContextmenu(v);
};

const onCurrentContextmenuClick = async ({ menuItem, contextItem }) => {
  switch (menuItem.action) {
    case 'download':
      generationStore.handleDownload(generationStore.previewImage)
      break

    case 'copy':
      try {
        // 构建复制内容
        const copyContent = generationStore.info

        await navigator.clipboard.writeText(copyContent)
        ElMessage.success('标签已复制到剪贴板')
      } catch (err) {
        ElMessage.error('复制失败，请检查浏览器权限')
        console.error('复制操作失败:', err)
      }
      break
  }
}

const prevImage = () => {
  if (generationStore.images.length === 0) return;

  const currentIndex = generationStore.images.indexOf(generationStore.previewImage);
  let newIndex = currentIndex - 1;

  if (newIndex < 0) {
    // 如果是第一张，则循环到最后一张
    newIndex = generationStore.images.length - 1;
  }

  generationStore.previewImage = generationStore.images[newIndex];
};

const nextImage = () => {
  if (generationStore.images.length === 0) return;

  const currentIndex = generationStore.images.indexOf(generationStore.previewImage);
  let newIndex = currentIndex + 1;

  if (newIndex >= generationStore.images.length) {
    // 如果是最后一张，则循环到第一张
    newIndex = 0;
  }

  generationStore.previewImage = generationStore.images[newIndex];
};

// 重置缩放（需要给 el-image 添加 ref 才能实现）
const previewImageRef = ref();
const resetZoom = () => {
  if (previewImageRef.value) {
    // 调用 el-image 的 setScale 方法重置缩放
    previewImageRef.value.setScale(1);
  }
};
</script>

<template>
  <el-card class="preview-container">
    <template #header>
      <div class="header-content">
        <div class="header-left">
          <h2 class="header-title">{{ $t('message.preview.title') }}</h2>
        </div>
        <div class="header-actions">
          <el-button
            :loading="generationStore.isJob"
            type="primary"
            @click="generationStore.generateImages"
            icon="ele-Promotion"
            class="generate-btn"
          >
            <span class="btn-text">{{ $t('message.preview.generate') }}</span>
            <span class="btn-icon">
              <el-icon><MagicStick /></el-icon>
            </span>
          </el-button>

          <el-popover
            placement="bottom-end"
            :width="420"
            trigger="hover"
            popper-class="info-popover"
          >
            <template #reference>
              <el-button type="info" icon="ele-InfoFilled" plain class="info-btn">
                {{ $t('message.preview.information') }}
              </el-button>
            </template>
            <div class="metadata-container">
              <div class="metadata-header">
                <el-icon><InfoFilled /></el-icon>
                <span>{{ $t('message.preview.metaData') }}</span>
              </div>
              <div class="metadata-content">
                <pre>{{ generationStore.info }}</pre>
              </div>
              <div class="metadata-actions">
                <el-button
                  type="primary"
                  size="default"
                  @click.stop="onCurrentContextmenuClick({ menuItem: { action: 'copy' } })"
                  class="copy-btn"
                >
                  <el-icon><DocumentCopy /></el-icon>
                  {{ $t('message.preview.copyText') }}
                </el-button>
                <el-button type="success" size="default" @click="generationStore.handleDownload(generationStore.previewImage)">
                  <el-icon><Download /></el-icon>
                  {{ $t('message.common.save') }}
                </el-button>
              </div>
            </div>
          </el-popover>
        </div>
      </div>
    </template>

    <!-- 主预览区域 -->
    <div class="preview-main">
      <div
        class="preview-wrapper"
        @contextmenu.prevent="onContextmenu(v, $event)"
        :class="{ 'loading-state': !generationStore.previewImage }"
      >
        <el-image
          :src="generationStore.previewImage"
          :preview-src-list="generationStore.images"
          class="preview-image"
          fit="contain"
          hide-on-click-modal
        >
          <template #error>
            <div class="image-slot error">
              <el-icon><Picture /></el-icon>
              <p>{{ $t('message.preview.loadFailed') }}</p>
            </div>
          </template>
          <template #placeholder>
            <div class="image-slot loading">
              <div class="loading-spinner">
                <div class="spinner-circle"></div>
              </div>
              <p>{{ $t('message.preview.loading') }}</p>
            </div>
          </template>
        </el-image>

        <!-- 预览操作工具栏 -->
        <div class="preview-toolbar">
          <el-tooltip effect="dark" :content="$t('message.preview.resetZoom')" placement="top">
            <div class="toolbar-btn" @click="resetZoom">
              <el-icon><FullScreen /></el-icon>
            </div>
          </el-tooltip>

          <el-tooltip effect="dark" :content="$t('message.preview.download')" placement="top">
            <div class="toolbar-btn" @click="generationStore.handleDownload(generationStore.previewImage)">
              <el-icon><Download /></el-icon>
            </div>
          </el-tooltip>

          <el-tooltip effect="dark" :content="$t('message.preview.previous')" placement="top">
            <div class="toolbar-btn" @click="prevImage">
              <el-icon><ArrowLeft /></el-icon>
            </div>
          </el-tooltip>

          <el-tooltip effect="dark" :content="$t('message.preview.next')" placement="top">
            <div class="toolbar-btn" @click="nextImage">
              <el-icon><ArrowRight /></el-icon>
            </div>
          </el-tooltip>
        </div>
      </div>
    </div>

    <!-- 缩略图区域 -->
    <div class="thumbnail-section">
      <div class="thumbnail-header">
        <el-text class="thumbnail-title">{{ $t('message.preview.generatedImages') }}</el-text>
        <el-text type="info" class="thumbnail-count">{{ generationStore.images.length }} {{ $t('message.preview.items') }}</el-text>
      </div>

      <div class="thumbnail-container">
        <div
          v-for="(image, index) in generationStore.images"
          :key="index"
          class="thumbnail-item"
          :class="{ 'active-thumbnail': generationStore.previewImage === image }"
          @click="openPreview(image)"
        >
          <el-image :src="image" class="thumbnail-image" />
          <div class="thumbnail-index">{{ index + 1 }}</div>
        </div>
      </div>
    </div>

    <!-- 进度条 -->
    <template #footer>
      <div class="progress-container">
        <div class="progress-header">
          <span class="progress-title">{{ $t('message.preview.generationProgress') }}</span>
        </div>
        <el-progress
          :percentage="generationStore.progress"
          :status="generationStore.progress === 100 ? 'success' : ''"
          :stroke-width="16"
          striped
          striped-flow
          :duration="10"
          class="progress-bar"
        />
      </div>
    </template>

    <Contextmenu
      :dropdown="state.dropdown"
      :menu-items="state.customMenuItems"
      ref="contextmenuRef"
      @currentContextmenuClick="onCurrentContextmenuClick"
    />
  </el-card>
</template>

<style scoped lang="scss">
.preview-container {
  border-radius: 16px;
  box-shadow: var(--el-box-shadow-light);
  overflow: hidden;
  border: none;
  background: var(--el-bg-color-overlay);

  :deep(.el-card__header) {
    background: linear-gradient(135deg, var(--el-color-primary-light-9) 0%, var(--el-bg-color) 100%);
    border-bottom: 1px solid var(--el-border-color-lighter);
    padding: 20px 28px;
  }

  :deep(.el-card__body) {
    padding: 0;
  }
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.header-left {
  .header-title {
    font-size: 22px;
    font-weight: 700;
    color: var(--el-text-color-primary);
    margin-bottom: 4px;
    letter-spacing: -0.3px;
  }
}

.header-actions {
  display: flex;
  gap: 12px;
}

.generate-btn {
  background: linear-gradient(135deg, var(--el-color-primary) 0%, var(--el-color-primary-dark-2) 100%);
  border: none;
  color: var(--el-color-white);
  font-weight: 600;
  padding: 12px 20px;
  border-radius: 12px;
  box-shadow: 0 4px 12px var(--next-box-shadow-dark);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;

  .btn-text {
    margin-right: 8px;
  }

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px var(--next-box-shadow-hover);
  }

  &:active {
    transform: translateY(0);
  }
}

.info-btn {
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  color: var(--el-text-color-secondary);
  font-weight: 500;
  padding: 11px 18px;
  border-radius: 12px;
  transition: all 0.2s ease;

  &:hover {
    background: var(--el-fill-color-light);
    border-color: var(--el-border-color-hover);
  }
}

.preview-main {
  padding: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 480px;
  background-color: var(--el-fill-color-lighter);
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.preview-wrapper {
  position: relative;
  width: 100%;
  max-width: 800px;
  height: 100%;
  min-height: 400px;
  display: flex;
  justify-content: center;
  align-items: center;
  background:
    linear-gradient(45deg, var(--el-fill-color-lighter) 25%, transparent 25%),
    linear-gradient(-45deg, var(--el-fill-color-lighter) 25%, transparent 25%),
    linear-gradient(45deg, transparent 75%, var(--el-fill-color-lighter) 75%),
    linear-gradient(-45deg, transparent 75%, var(--el-fill-color-lighter) 75%);
  background-size: 20px 20px;
  background-position: 0 0, 0 10px, 10px -10px, -10px 0px;
  border-radius: 12px;
  box-shadow: inset 0 0 12px rgba(0,0,0,0.04);

  &.loading-state {
    background: var(--el-fill-color-lighter);
    box-shadow: none;
  }
}

.preview-image {
  max-height: 50%;
  max-width: 50%;
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
  transition: all 0.3s ease;
  object-fit: contain;
}

.preview-toolbar {
  position: absolute;
  bottom: 24px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 12px;
  background: rgba(var(--el-bg-color-rgb), 0.92);
  backdrop-filter: blur(10px);
  border-radius: 50px;
  padding: 8px 16px;
  box-shadow: var(--el-box-shadow-light);
  border: 1px solid var(--el-border-color);
  z-index: 10;
}

.toolbar-btn {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color);
  color: var(--el-text-color-secondary);
  cursor: pointer;
  transition: all 0.2s ease;

  &:hover {
    background: var(--el-fill-color-lighter);
    transform: translateY(-2px);
    box-shadow: var(--el-box-shadow-light);
  }
}

.image-slot {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  color: var(--el-text-color-placeholder);

  &.error {
    .el-icon {
      font-size: 72px;
      color: var(--el-border-color);
      margin-bottom: 16px;
    }

    p {
      font-size: 16px;
      font-weight: 500;
      color: var(--el-text-color-placeholder);
    }
  }

  &.loading {
    p {
      margin-top: 24px;
      font-size: 16px;
      color: var(--el-text-color-secondary);
      font-weight: 500;
    }
  }
}

.loading-spinner {
  width: 60px;
  height: 60px;
  position: relative;

  .spinner-circle {
    width: 100%;
    height: 100%;
    border: 4px solid var(--el-color-primary-light-8);
    border-top: 4px solid var(--el-color-primary);
    border-radius: 50%;
    animation: spinner-rotate 1.2s linear infinite;
  }
}

@keyframes spinner-rotate {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.thumbnail-section {
  padding: 20px 28px;
  background-color: var(--el-bg-color);

  .thumbnail-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }

  .thumbnail-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }

  .thumbnail-count {
    font-size: 14px;
    font-weight: 500;
    color: var(--el-text-color-secondary);
  }
}

.thumbnail-container {
  display: flex;
  gap: 16px;
  overflow-x: auto;
  padding: 8px 0 16px;
  scrollbar-width: thin;

  &::-webkit-scrollbar {
    height: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background: var(--el-border-color);
    border-radius: 10px;
  }
}

.thumbnail-item {
  position: relative;
  flex: 0 0 auto;
  width: 120px;
  height: 80px;
  border-radius: 10px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: var(--el-box-shadow-light);
  border: 2px solid transparent;

  &:hover {
    transform: translateY(-5px);
    box-shadow: var(--el-box-shadow);
  }

  &.active-thumbnail {
    border-color: var(--el-color-primary);
    box-shadow: 0 0 0 3px var(--el-color-primary-light-5);
  }
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.thumbnail-index {
  position: absolute;
  bottom: 5px;
  right: 5px;
  background: rgba(0, 0, 0, 0.7);
  color: var(--el-color-white);
  width: 24px;
  height: 24px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
}

.progress-container {
  padding: 20px 28px;
  background-color: var(--el-fill-color-lighter);
  border-top: 1px solid var(--el-border-color-lighter);

  .progress-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 12px;
  }

  .progress-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.metadata-container {
  position: relative;
  padding: 16px;

  .metadata-header {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    margin-bottom: 16px;

    .el-icon {
      color: var(--el-color-primary);
    }
  }

  .metadata-content {
    pre {
      padding: 16px;
      background-color: var(--el-fill-color-lighter);
      border-radius: 8px;
      max-height: 200px;
      overflow: auto;
      font-size: 14px;
      line-height: 1.6;
      white-space: pre-wrap;
      font-family: monospace;
      color: var(--el-text-color-regular);
      border: 1px solid var(--el-border-color);
    }
  }

  .metadata-actions {
    display: flex;
    gap: 10px;
    margin-top: 16px;
    justify-content: flex-end;
  }
}

.info-popover {
  border-radius: 12px !important;
  box-shadow: var(--el-box-shadow-dark) !important;
  border: 1px solid var(--el-border-color) !important;
  background-color: var(--el-bg-color-overlay);
}
</style>
